<!DOCTYPE html>
<html>

<head>
      <title>阿里云图片上传</title>
      <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="./Base64.js"></script>
</head>

<body>
      <canvas id="canvas" style="display: none;"></canvas>
      <div class="container" style="padding: 100px;">
            <form id="form1" enctype="multipart/form-data">
                  <legend>阿里云图片上传</legend>
                  <div class="form-group">
                        <input type="hidden" class="form-control" id="name" name="name" value="">
                        <input type="hidden" class="form-control" id="key" name="key" value="image/Temp/ApprovalTask/${filename}">
                        <input type="hidden" class="form-control" id="policy" name="policy" value="">
                        <input type="hidden" class="form-control" id="OSSAccessKeyId" name="OSSAccessKeyId" value="LTAI3M6GxA5Cvfev">
                        <input type="hidden" class="form-control" id="success_action_status" name="success_action_status" value="200">
                        <input type="hidden" class="form-control" id="signature" name="signature" value="ORlRS5Sfk6m55AcxUN0+/JDuk2c=">
                        <label for="file1">选择要上传的图片</label>
                        <input type="file" class="btn btn-default" name="file1" id="file1" onchange="fileSelected();" />
                  </div>
                  <div class="form-group">
                        <ul class="list-group">
                              <li id="fileName" class="list-group-item">Name:</li>
                              <li id="fileSize" class="list-group-item">Size:</li>
                              <li id="fileType" class="list-group-item">Type:</li>
                        </ul>
                  </div>
                  <div class="form-group">
                        <input type="button" class="btn btn-primary" onclick="uploadFile()" value="上传" />
                  </div>
                  <div id="progressNumber"></div>
                  <div class="form-group">
                        <img id="img" src="" alt="">
                  </div>
                  <div class="form-group">
                        <img id="preview" src="" style="display: none;">
                  </div>
                  <div class="form-group">
                        <img width="400" id="Cpreview" src="">
                  </div>

            </form>
      </div>
      <script type="text/javascript">

            var fileDate    //防止多次提交

            window.onload = function () {

                  var policyText = {
                        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                        "conditions": [
                              ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
                        ]
                  };

                  //加密
                  var policyBase64 = new Base64().encode(JSON.stringify(policyText))

                  $("policy").value = policyBase64;

            }

            //随机字符串
            function random_string(len) {
                  len = len || 32;
                  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
                  var maxPos = chars.length;
                  var pwd = '';
                  for (i = 0; i < len; i++) {
                        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
                  }
                  return pwd;
            }

            //ID选择器
            function $(str) { return document.getElementById(str); }

            //图片预览
            function imgPreview(file) {

                  var reader = new FileReader();

                  reader.readAsDataURL(file);

                  reader.onloadend = function () {

                        $('preview').src = reader.result;

                        $('preview').onload = function(){
                              canvasImg($('preview'));
                        }

                  }

            }

            //canvas图片压缩
            function canvasImg(source) {

                  var preview = $('Cpreview');
                  var canvas = $('canvas');
                  //图片宽高
                  var width = source.width;
                  var height = source.height;

                  //宽高比例
                  var scale = width / height;

                  //初始化 canvas
                  var context = canvas.getContext('2d');

                  //裁剪前的图片 格式
                  var sx = 0;
                  var sy = 0;
                  var sWidth = width;
                  var sHeight = height;

                  //裁剪后的图片 格式
                  var dx = 0;
                  var dy = 0;
                  var dWidth = 400;
                  var dHeight = dWidth / scale;

                  //图片清晰度
                  var quality = 0.8;

                  canvas.width = dWidth;
                  canvas.height = dHeight;

                  //压缩
                  context.drawImage(source, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

                  //图片base 64
                  var dataUrl = canvas.toDataURL('image/jpg', quality);

                  //预览压缩后的图片
                  // preview.src = dataUrl;

                  canvas.toBlob(function (blob) {

                        uploadFile(blob);

                        url = URL.createObjectURL(blob);
                        preview.src = url;

                  });
            }

            //选择图片 获取图片信息
            function fileSelected() {

                  var file = $('file1').files[0];
                  imgPreview(file);

                  if (file) {
                        var fileSize = 0;
                        if (file.size > 1024 * 1024) fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
                        else fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
                        $('fileName').innerHTML = 'Name: ' + file.name;
                        $('fileSize').innerHTML = 'Size: ' + fileSize;
                        $('fileType').innerHTML = 'Type: ' + file.type;
                  }

                  $('name').value = file.name;

                  var ramdomName = random_string(10) + $('file1').value.match(/\.?[^.\/]+$/);

                  $('key').value = $('key').value.replace("${filename}", ramdomName);

            }

            //发送请求上传图片
            function uploadFile(blob) {

                  //没有数据和重复数据 不能提交
                  if ($('file1').files[0] != undefined && fileDate != $('file1').files[0]) {

                        fileDate = $('file1').files[0];

                        var fd = new FormData($('form1'));

                        fd.append('file',blob);

                        var xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener("progress", uploadProgress, false);
                        xhr.addEventListener("load", uploadComplete, false);
                        xhr.addEventListener("error", uploadFailed, false);
                        xhr.addEventListener("abort", uploadCanceled, false);
                        xhr.open("POST", "http://flm158.oss-cn-shanghai.aliyuncs.com");
                        xhr.send(fd);
                  }

            }

            //进度条
            function uploadProgress(evt) {
                  if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        $('progressNumber').innerHTML = '上传完成：' + percentComplete.toString() + '%';
                  } else { $('progressNumber').innerHTML = 'unable to compute'; }
            }

            //上传完成
            function uploadComplete(evt) { /* This event is raised when the server send back a response */ console.log(evt.target.responseText);
                  $('img').src = 'http://flm158.oss-cn-shanghai.aliyuncs.com/' + $('key').value;
            }

            //上传失败
            function uploadFailed(evt) { alert("There was an error attempting to upload the file."); }

            function uploadCanceled(evt) { alert("The upload has been canceled by the user or the browser dropped the connection."); }
      </script>
</body>

</html>